# encoding=utf-8

import sys, os
if hasattr(sys, 'frozen'):
    os.environ['PATH'] = sys._MEIPASS + ";" + os.environ['PATH']

import PyQt5.QtWidgets as qw
import ui_main
from PyQt5.QtCore import QTimer, Qt, pyqtSignal
import sys,time
import numpy as np
import random
import json

from mpl_toolkits.mplot3d import Axes3D
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.lines import Line2D
import matplotlib
import matplotlib.cbook as cbook

import logging
from serial import Serial
import threading
from time import sleep
from beken import Beken
from configparser import ConfigParser
from serial.serialutil import *
import serial.tools.list_ports

class Figure_Canvas(FigureCanvas):
    def __init__(self,parent=None,width=3.9,height=2.7,dpi=1000):
        self.fig=Figure(figsize=(width,height),dpi=100)
        super(Figure_Canvas,self).__init__(self.fig)
        self.ax=self.fig.add_subplot(111)
        # x=[1,2,3,4,5,6,7]
        # y=[2,1,3,5,6,4,3]
        # self.ax.plot(x,y)
        self.ax.set_title('RSSI monitor system' )
        self.ax.set_xlabel('Time (m)')
        self.ax.set_ylabel('Rssi_dev (m)')
        self.ax.grid()
        self.draw()

    def test(self):
        x=[1,2,3,4,5,6,7]
        y=[2,1,3,5,6,4,3]
        self.ax.plot(x,y)

class myWindow(qw.QMainWindow, ui_main.Ui_MainWindow):
    signal_recv_data = pyqtSignal(str)
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        # init gui
        # self.statusbar.showMessage("status:ok")
        
        self.Init_Widgets()
        self.timer=QTimer()
        self.timer.start(500)
        self.ts=time.time()
        self.timer.timeout.connect(self.UpdateImgs)

        self.pushButton.clicked.connect(self.pushButton_cb)
        self.pushButton_start.clicked.connect(self.pushButton_start_cb)
        self.pushButton_stop.clicked.connect(self.pushButton_stop_cb)

        # 自定义信号
        self.signal_recv_data.connect(self.show_data_cb)

        #################################################################################################
        # logging setup
        logging.basicConfig(level=logging.DEBUG,
                        format='[%(asctime)s] [%(levelname)s] %(message)s',
                        filename='log',
                        filemode='w')
        console = logging.StreamHandler()
        console.setLevel(logging.INFO)
        console.setFormatter(logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s'))
        self.logger = logging.getLogger('logger')
        self.logger.addHandler(console)

        #################################################################################################
        setupsconf = ConfigParser()
        setupsconf.read('setup.conf')
        user_port = setupsconf['serial']['user']

        print("com is %s" % user_port)
        # user_port = 'com4'
        #################################################################################################
        # definition
        self.uart_start = 0

        def check_valid_uart():
            ports_value = []
            ports_list = serial.tools.list_ports.comports()
            for i in range(len(ports_list)):
                ports_value.append(ports_list[i][0])
            # print("ports_value is ", ports_value)

            if (0 == len(ports_value)):
                print("can't find uart port.")
                self.comboBox_uart.clear()
                self.comboBox_uart.setCurrentIndex(-1)
            else:
                for i in range(len(ports_value)):
                    index = self.comboBox_uart.findText(ports_value[i], Qt.MatchFixedString)
                    if (index < 0):
                        self.comboBox_uart.addItem(ports_value[i])
                    # else:
                    #     print("curent port is ", self.comboBox_uart.currentText())

        # 开启监听线程
        def gui_status_thread():
            print("start gui_status_thread.")
            while(True):
                check_valid_uart()
                sleep(3)

        threading.Thread(target=gui_status_thread, daemon=True).start()

    def pushButton_cb(self):
        print("you clicked pushButton.")
        self.beken.com.sendMsgByName('wifi scan', {'ssid': None})

    def pushButton_start_cb(self):
        print("you clicked pushButton_start.")
        # get current port
        self.com_port = self.comboBox_uart.currentText()
        if (0 == self.uart_start):
            self.beken = Beken(self)
            self.uart_start = 1
        else:
            print("Already setup serial.")

    def pushButton_stop_cb(self):
        print("you clicked pushButton_stop.")

    def show_data_cb(self, data):
        print("recv uart data : ", data)
        if "dev" in data:
            data_dict = json.loads(data)
            dev = data_dict["dev"]
            data_y = float(dev)
            if (self.index_x <= 100):
                self.index_x += 1
                self.list_x.append(self.index_x)
                self.list_y.append(data_y)
            else:
                # 保持X轴数据不变，更新Y轴数据，将老的数据舍弃
                self.list_y.pop(0)
                self.list_y.append(data_y)
            # self.list_y.pop(0)
            # self.list_y.append(data_y)
            self.LineFigure.ax.clear()
            self.LineFigure.ax.plot(self.list_x, self.list_y)
            self.LineFigure.draw()

    def Init_Widgets(self):
        self.PrepareSamples()
        self.PrepareLineCanvas()

    def PrepareSamples(self):
        self.x = np.arange(0, 100, 0.02)
        self.y = np.arange(-4, 4, 0.02)
        self.z = np.sin(self.x)
        self.list_x = []
        # for i in range(0, 100):
        #     self.list_x.append(i)
        self.list_y = []
        # for i in range(0, 100):
        #     self.list_y.append(0)
        self.index_x = 0

    def PrepareLineCanvas(self):
        # 添加编辑框（QLineEdit）
        # self.lineEdit = qw.QLineEdit("0") # 注意QLineEdit("0") 内可以没self!!
        # 放入布局内
        self.LineFigure = Figure_Canvas()
        self.gridLayout.addWidget(self.LineFigure, 0, 0)
        # self.gridLayout.addWidget(self.lineEdit, 1, 0)
        self.LineFigure.ax.set_xlim(0, 100)
        self.LineFigure.ax.set_ylim(0, 10)
        # self.line = Line2D(self.x, self.z)
        # self.LineFigure.ax.add_line(self.line)

    def UpdateImgs(self):
        # dt=time.time()-self.ts
        # self.LineUpdate(dt)
        data_y = random.randint(1,10)
        if (self.index_x <= 100):
            self.index_x += 1
            self.list_x.append(self.index_x)
            self.list_y.append(data_y)
        else:
            # 保持X轴数据不变，更新Y轴数据，将老的数据舍弃
            self.list_y.pop(0)
            self.list_y.append(data_y)
        # self.list_y.pop(0)
        # self.list_y.append(data_y)
        self.LineFigure.ax.clear()
        self.LineFigure.ax.plot(self.list_x, self.list_y)
        self.LineFigure.draw()

    def LineUpdate(self,dt):
        z=np.sin(self.x+dt)
        self.line.set_ydata(z)
        self.LineFigure.draw()

# if __name__ == "__main__":
#     app = qw.QApplication(sys.argv)
#     w = myWindow()
#     w.show()

#     sys.exit(app.exec_())
